<script setup>
import { computed, ref, watch, onMounted, nextTick } from 'vue';
import { useOutputStore } from '../../stores/output';

const output = useOutputStore();
const containerRef = ref(null);

const channels = computed(() => Object.keys(output.channels));

function ensureActive() {
	if (!output.activeChannel) output.setActiveChannel('General');
	if (!output.channels[output.activeChannel]) output.append('General', '');
}

function onSelectChannel(name) { output.setActiveChannel(name); scrollToBottom(); }
function clear() { output.clear(output.activeChannel); nextTick(scrollToBottom); }
function scrollToBottom() { nextTick(() => { try { const el = containerRef.value; el && (el.scrollTop = el.scrollHeight); } catch {} }); }

onMounted(() => { ensureActive(); scrollToBottom(); });
watch(() => output.channels[output.activeChannel]?.lines?.length, scrollToBottom);
</script>

<template>
  <div class="flex h-full min-h-0">
    <aside class="w-36 border-r dark:border-neutral-800 p-2 text-[12px]">
      <div class="font-semibold mb-2">OUTPUT</div>
      <ul class="space-y-1">
        <li v-for="name in channels" :key="name">
          <button class="w-full text-left px-2 py-1 rounded hover:bg-slate-100 dark:hover:bg-neutral-800"
                  :class="name===output.activeChannel ? 'bg-subtle-bg' : ''"
                  @click="onSelectChannel(name)">{{ name }}</button>
        </li>
      </ul>
    </aside>
    <section class="flex-1 min-h-0 p-2 text-[12px]">
      <div class="mb-2 flex items-center justify-between">
        <div class="text-slate-500 dark:text-neutral-400 truncate">{{ output.activeChannel }}</div>
        <div>
          <button class="px-2 py-1 rounded hover:bg-slate-100 dark:hover:bg-neutral-800" @click="clear">Clear</button>
        </div>
      </div>
      <div ref="containerRef" class="h-full overflow-auto font-mono whitespace-pre-wrap leading-5 thin-scrollbar scrollbar-compact scrollbar-track">
        <div v-for="(line, i) in (output.channels[output.activeChannel]?.lines || [])" :key="i">
          {{ line.text }}
        </div>
      </div>
    </section>
  </div>
</template>


